#!/usr/bin/env php
<?php

/*

HTTPSEverywhere for Desktopd
Copyright (C) 2015  Desktopd Developer(s)

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

https://www.gnu.org/licenses/agpl.html

*/


/**
    An illustrative use of PHP HTTPS Everywhere (HTTPS Everywhere for Desktopd)
    Works as a 'redirect_program' for a Squid proxy server. [1]
    
    This is a functional equivalent of squid.pl in perl-HTTPSEverywhere. [2]
    
    [1]: http://www.squid-cache.org/Doc/config/redirect_program/
    [2]: https://github.com/mikecardwell/perl-HTTPSEverywhere
*/


use Desktopd\HTTPSEverywhere\HTTPSEverywhere;


// autoloader
require_once dirname(__DIR__) . '/tests/autoloader.php';


$input = defined('STDIN') && is_resource(STDIN) ? STDIN : fopen('php://stdin', 'rb');
if (!is_resource($input)) {
    file_put_contents('php://stderr', "Failed to open the input stream\n");
    exit(1);
}


/*
    Set up HTTPS Everywhere.
    This can take up to thousands of milliseconds.
*/

$ruleDir = dirname(__DIR__) . '/https-everywhere/https-everywhere/src/chrome/content/rules';
$userRuleDir = dirname(__DIR__) . '/https-everywhere/HTTPSEverywhereUserRules';
$httpsEverywhere = new HTTPSEverywhere($ruleDir, $userRuleDir);

file_put_contents('php://stderr', sprintf(
    "[HTTPS Everywhere] %d ruleset(s) available\n"
    , count($httpsEverywhere)
));

$time = time(); // timestamp


$total = 0;
$rewrittenCount = 0;
while (!feof($input)) {
    if (!is_resource($input)) {
        file_put_contents('php://stderr', "Invalid input stream\n");
        break;
    }
    
    $line = explode(' ', trim(fgets($input)), 2)[0];
    
    if ('' === $line) {
        // At the end of the stream, we need to read an empty line
        // but an empty line does not mean the end of the stream
        // this also occurs when the timeout is hit (trim(false) === '')
        continue;
    }
    
    // refresh rulesets every 3600 seconds
    if (time() - $time >= 3600) {
        $httpsEverywhere = new HTTPSEverywhere($ruleDir, $userRuleDir);
        file_put_contents('php://stderr', sprintf(
            "[HTTPS Everywhere] %d ruleset(s) available\n"
            , count($httpsEverywhere)
        ));
        $time = time();
    }
    
    // rewrite!
    $rewritten = $httpsEverywhere->rewrite($line);
    if ($rewritten !== $line) {
        // rewritten
        echo '301:', $rewritten, PHP_EOL;
        $rewrittenCount++;
    } else {
        // not rewritten
        echo $line, PHP_EOL;
    }
    $total++;
}

file_put_contents('php://stderr', "[HTTPS Everywhere] Processed: $total, Rewritten: $rewrittenCount\n");


// vim: ts=4 et ai

